using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;

namespace DBRestriker.Forms
{
	class InfoBox : RichTextBox
	{
		private const byte MAX_INFO_LINECOUNT = 50;
		private bool _autoScroll;

		public InfoBox()
		{
			TextChanged += TextChangedEventHandler;
		}

		/// <summary>
		/// Gets or sets a value indicating whether the box scrolls to the end when the text has changed.
		/// </summary>
		/// <value><c>true</c> if auto scroll is enabled; otherwise, <c>false</c>.</value>
		[Category("Behavior")]
		public bool AutoScroll
		{
			get { return _autoScroll; }
			set { _autoScroll = value; }
		}

		internal void AppendException(Exception exc)
		{
			AppendLine(exc.Message);
		}

		internal void AppendLine(string line)
		{
			if (0 < TextLength)
			{
				if (MAX_INFO_LINECOUNT <= Lines.Length)
				{
					// Drop first line
					List<string> infoList = new List<string>(MAX_INFO_LINECOUNT);
					bool firstLine = true;
					foreach (string infoLine in Lines)
					{
						if (firstLine)
						{
							firstLine = false;
						}
						else
						{
							infoList.Add(infoLine);
						}
					}
					Lines = infoList.ToArray();
				}
				AppendText(string.Format("{0}{1}", Environment.NewLine, line));
			}
			else
			{
				AppendText(line);
			}
		}

		internal void AppendLine(string format, params object[] args)
		{
			AppendLine(string.Format(format, args));
		}

		private void TextChangedEventHandler(object sender, EventArgs e)
		{
			if (AutoScroll)
			{
				SelectionStart = TextLength;
				SelectionLength = 0;
				ScrollToCaret();
			}
		}
	}
}
